
module Content
  class Document < Field

    attr_accessor :persisted

#    def initialize
#      super()
#      @fields = []
#    end
#
#    def add_child o
#      super(o).tap { |child|
#        if child.class.ancestors.include? Field
#          @fields << child
#        end
#      }
#    end

#    def static
#      @fields.each { |field| field.static }
#      self
#    end

#    def editable
#      super()
#      children = self.children.dup
#      self.children = []
#
#      add(DrunkenMaster::Form.new(:action => callback(:save))) do
#        if self.persisted
#          e :input,
#            :type => 'hidden',
#            :name => 'uuid',
#            :value => self.persisted.uuid
#        end
#
#        add_many children
#
#        e :input, :type => 'submit', :value => 'save'
#      end
#      self
#    end

    def save
      params = context.request.params
      if params['uuid']
        doc = self.class.get(params['uuid'])
      else
        doc = self
      end
      p "setting params #{params.inspect}"
      doc.value = params

      p "saving"
      Document.repository.put(doc.persisted || doc)
    end

    def self.get uuid
      Document.repository.get(uuid).object
    end

    def self.remove uuid
      Document.repository.remove(uuid).object
    end

    def serialize_to_hash
      value.tap { |v|
        p "my value is #{v.inspect}"
      }
    end

    def self.unserialize_hash hash
      p "unserialize form #{hash.inspect}"
      self.new.tap { |document|
        document.value = hash
      }
    end

    @@repo = nil

    def self.repository= repository
      puts "My repo is set to #{repository}"
      @@repo = repository
    end

    def self.repository
      @@repo
    end

  end
end